package netbridge

import (
	"log"

	"github.com/vishvananda/netlink"
)

const NET_BRIDGE_A_0 = "br100"

func init() {
	log.SetPrefix("[netbridge]")
}

func Run() {
	// 创建网桥
	bridge := &netlink.Bridge{
		LinkAttrs: netlink.LinkAttrs{
			Name: NET_BRIDGE_A_0,
			MTU:  1500,
		},
	}
	if err := netlink.LinkAdd(bridge); err != nil {
		log.Fatalf("Failed to create bridge: %v", err)
	}
	log.Printf("网桥%s创建成功\n", NET_BRIDGE_A_0)

	// 获取刚才创建的网桥
	brFd, err := netlink.LinkByName(NET_BRIDGE_A_0)
	if err != nil {
		log.Fatalf("Failed to get bridge: %v", err)
	}
	log.Printf("网桥获取成功,fd:%d\n", brFd)
	// 设置网桥状态为 UP
	if err := netlink.LinkSetUp(brFd); err != nil {
		log.Fatalf("Failed to set bridge up: %v", err)
	}
	log.Printf("网桥激活成功,fd:%d\n", brFd)
	// 创建 veth pair
	veth1 := &netlink.Veth{
		LinkAttrs: netlink.LinkAttrs{Name: "veth1", MTU: 1500},
		PeerName:  "veth2",
	}
	if err := netlink.LinkAdd(veth1); err != nil {
		log.Fatalf("Failed to create veth pair: %v", err)
	}

	// 获取 veth 接口
	link1, err := netlink.LinkByName("veth1")
	if err != nil {
		log.Fatalf("Failed to get veth1: %v", err)
	}

	link2, err := netlink.LinkByName("veth2")
	if err != nil {
		log.Fatalf("Failed to get veth2: %v", err)
	}

	// 将 veth1 添加到网桥 br0
	if err := netlink.LinkSetMaster(link1, brFd); err != nil {
		log.Fatalf("Failed to add veth1 to bridge: %v", err)
	}

	// 设置 veth1 和 veth2 的状态为 UP
	if err := netlink.LinkSetUp(link1); err != nil {
		log.Fatalf("Failed to set veth1 up: %v", err)
	}

	if err := netlink.LinkSetUp(link2); err != nil {
		log.Fatalf("Failed to set veth2 up: %v", err)
	}

	log.Println("Bridge created and veth pair added successfully.")
}
